﻿using Exam.infranstuctrue.Dto.Respones;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System.Text;

namespace Exam.Filters
{
    public class ActionLogAttribute:BaseAttribute
    {
        public string? group { get; set; }
        public string? name { get; set; }
        public override void OnActionExecuted(ActionExecutedContext context)
        {
            var c = (context.Result as ObjectResult)?.Value;
            if (c is ApiResult)
            {
                string paras = "";
                if (context.HttpContext.Request.Method.ToUpper() == "GET")
                {
                    var keys = context.HttpContext.Request.Query.Keys;
                    foreach (var item in keys)
                    {
                        paras += $"{item}={context.HttpContext.Request.Query[item]};";
                    }
                }
                else
                {
                    var request = context.HttpContext.Request;
                    request.EnableBuffering();
                    if (request.Method.ToLower().Equals("post"))
                    {
                        request.Body.Seek(0, SeekOrigin.Begin);
                        using var reader = new StreamReader(request.Body, Encoding.UTF8);
                        paras = reader.ReadToEnd();
                    }
                }
                var url = context.HttpContext.Request.Path;
                var result = c as ApiResult;
                var FileName = DateTime.Now.ToString("yyyyMMdd") + ".txt";
                System.IO.File.AppendAllText(@"E:\S4\日志\Logs\" + FileName, $"返回结果【{result?.code}】,返回消息【{result?.message}】,行为【{this.name}】,组【{this.group}】" +
                    $"地址【{url}】,参数【{paras}】,IP【{this.GetIp()}】");
            }
        }
    }
}
